package main

import (
	"fmt"
	"io"
	"net"
	"time"
	"zinx/utils"
	"zinx/znet"
)

func main() {
	fmt.Println("client start...")
	//连接服务器
	conn,err := net.Dial("tcp","127.0.0.1:8999")
	if err != nil{
		fmt.Printf("dial error:%v\n",err)
		return
	}
	//休息一秒，让服务器那边先启动服务器
	time.Sleep(1 * time.Second)
	dp := znet.NewDataPack()
	headBuf := make([]byte,dp.GetHeadLen())

	//每隔一秒给服务器那边发送数据，并接收服务器发送过来的数据
	for{
		//自己准备点数据，发送给服务器
		bytes,err := dp.Pack(znet.NewMsgPackage(0,[]byte("zinx V0.5 Client test message")))
		if err != nil{
			fmt.Printf("client pack msg error:%v\n",err)
			return
		}
		// 发送过去
		_,err = conn.Write(bytes)
		if err != nil{
			fmt.Printf("client write msg to server error:%v\n",err)
			return
		}

		//接收服务器发送过来的数据，这里要注意粘包问题
		//第一次读头部数据
		if _,err = io.ReadFull(conn,headBuf);err != nil{
			fmt.Printf("client recv head error:%v\n",err)
			return
		}
		msg,err := dp.UnPack(headBuf)
		if err != nil{
			fmt.Printf("client UnPack msg error:%v\n",err)
			return
		}
		//第二次读有效数据
		if msg.GetMsgLen() > 0 && msg.GetMsgLen() < utils.GlobalObject.MaxPackageSize{
			dataBuf := make([]byte,msg.GetMsgLen())
			if _,err = io.ReadFull(conn,dataBuf);err != nil{
				fmt.Printf("client recv data error:%v\n",err)
				return
			}
			msg.SetData(dataBuf)
			//将数据打印出来
			fmt.Printf("--->client Recv server msg: MsgID = %d,dataLen = %d,data = %s\n",
						msg.GetMsgID(),msg.GetMsgLen(),msg.GetMsgData())
		}

		time.Sleep(1 * time.Second)
	}
}